package com.kmt.plaza.sevice.impl;

import com.kmt.plaza.dao.UserAddressMapper;
import com.kmt.plaza.entity.UserAddress;
import com.kmt.plaza.sevice.UserAddressService;
import com.kmt.plaza.vo.ResStatus;
import com.kmt.plaza.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserAddressImpl implements UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;
    private Logger logger = LoggerFactory.getLogger(UserAddressImpl.class);

    @Override
    public ResultVO queryAddress(Integer userId) {
        List<UserAddress> list = userAddressMapper.queryUserAddress(userId);
        if(list.size()>0){
            return new ResultVO(ResStatus.OK,"success",list);
        }
        return new ResultVO(ResStatus.NO,"fail",null);
    }

    @Override
    public int insertAddress(UserAddress userAddress) {
        logger.info("新增地址开始......");
        //查出所有的地址
        int userId = Integer.parseInt(userAddress.getUserId());
        List<UserAddress> lists = userAddressMapper.queryUserAddress(userId);
        //如果传过来的默认地址为1
        Integer defaultAddress = userAddress.getDefaultAddress();
        if(defaultAddress==1){
            for (int i = 0; i <lists.size() ; i++) {
                //将查到的数据的默认地址改为0
                int j = lists.get(i).getDefaultAddress();
                if(j==1){
                    defaultAddress=0;
                }
            }
            int n = userAddress.getDefaultAddress();
            int m = userAddressMapper.insertAddress(userAddress);
        }else {
            int m = userAddressMapper.insertAddress(userAddress);
        }
        return userId;
    }

    @Override
    public ResultVO deleteAddress(Integer addressId) {
        logger.info("删除地址开始......");
        Example example = new Example(UserAddress.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("addressId",addressId);
        int i = userAddressMapper.deleteByExample(example);
        if(i>0){
            return new ResultVO(ResStatus.OK,"删除成功！",null);
        }else{
            return new ResultVO(ResStatus.NO,"删除失败！",null);
        }
    }

    @Override
    public int updateAddress(UserAddress userAddress) {
        logger.info("修改地址开始......");
        return userAddressMapper.updateAddress(userAddress);

    }


}
